﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OleDb;
using System.Data;

namespace QLHocSinh.DAO
{
    public class OleDbDataAccessHelper : DataAccessHelper
    {
        public OleDbDataAccessHelper()
        {
            strConnection = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=QuanLyHocSinh.mdb";
        }

        public override System.Data.DataTable ExecuteQuery(string strQuery)
        {
            DataTable resTable = new DataTable();

            OleDbConnection _con = new OleDbConnection(strConnection);
            try
            {
                _con.Open();
                OleDbDataAdapter adapter = new OleDbDataAdapter(strQuery, _con);
                adapter.Fill(resTable);
            }
            catch (Exception ex)
            {
                throw new Exception("Loi khi thuc thi lenh SQL: " + ex.Message);
            }
            finally
            {
                _con.Close();
            }

            return resTable;
        }

        public override void ExecuteNonQuery(string strQuery)
        {
            OleDbConnection _con = new OleDbConnection(strConnection);

            try
            {
                _con.Open();
                OleDbCommand command = _con.CreateCommand();
                command.CommandText = strQuery;
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new Exception("Loi khi thuc thi lenh SQL: " + ex.Message);
            }
            finally
            {
                _con.Close();
            }
        }

        public override DataTable ExecuteProcedure(string storeProcName, Dictionary<string, object> para)
        {
            DataTable resTable = new DataTable();
            OleDbConnection _con = new OleDbConnection(strConnection);
            try
            {
                _con.Open();

                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = _con;
                cmd.CommandText = storeProcName;
                cmd.CommandType = CommandType.StoredProcedure;

                
                foreach (KeyValuePair<string, object> pair in para)
                {
                    OleDbParameter oledbParam = new OleDbParameter(pair.Key, pair.Value);
                    cmd.Parameters.Add(oledbParam);
                }

                OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
                adapter.Fill(resTable);

                _con.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("Loi khi thuc thi store procedure: " + ex.Message);
            }

            return resTable;
        }
    }
}
